package com.example.cdpbookstore.web.servlet;

import cn.hutool.crypto.digest.BCrypt;
import com.example.cdpbookstore.pojo.entity.Customer;
import com.example.cdpbookstore.service.CustomerService;
import com.example.cdpbookstore.service.impl.CustomerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@WebServlet("/forget")
public class ForgetServlet extends HttpServlet {
    private final CustomerService customerService = new CustomerServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");


        String emailErr = null;
        String captchaErr = null;
        // 邮件查重
        Customer customer = customerService.getByUsernameOrEmail(email);
        if (customer == null) {
            emailErr = "当前邮箱没有注册";
            req.setAttribute("emailErr", emailErr);
        }
        // 验证码比对
        String captcha1 = (String) req.getSession().getAttribute("captcha");
        System.out.println("校验的验证码是：" + captcha1);
        if (!captcha.equals(captcha1)) {
            captchaErr = "验证码错误";
            req.setAttribute("captchaErr", captchaErr);
        }

        if (emailErr != null || captchaErr != null) {
            req.getRequestDispatcher("forget.jsp").forward(req, resp);
            return;
        }


        customer.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));

        LocalDateTime now = LocalDateTime.now();
        customer.setUpdateTime(now);

        if (customerService.update(customer)) {
            // 页面跳转
            req.setAttribute("page", "login.jsp");
            req.setAttribute("message", "重置密码成功");
            req.getRequestDispatcher("delay_jump.jsp").forward(req, resp);
        } else {
            // 页面跳转
            req.setAttribute("page", "forget.jsp");
            req.setAttribute("message", "重置密码失败");
            req.getRequestDispatcher("delay_jump.jsp").forward(req, resp);
        }
    }
}
